using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using oms.Modules.System.Models;
using oms.Shared.Data;
using oms.Shared.Services.Redis;
using oms.Shared.utils;

namespace oms.Modules.Test;

public partial class Test(AppDbContext dbContext, ILogger<Test> logger, IRedisService redisService)
    : ComponentBase{



    private string? DbResult { get; set; }

    private string? RedisResult { get; set; }
    
    private string? DbQueryResult { get; set; }


    // 页面初始化时自动执行（组件加载后立即触发）
    protected override async Task OnInitializedAsync()
    {
        await TestDbConnection();
        await TestRedisConnection();

        await TestDbQuery();

        await TestPassword();

    }

    private async Task TestDbConnection()
    {
        try
        {
            await dbContext.Database.OpenConnectionAsync();
            DbResult = "✅ 连接成功！数据库可访问。";
            logger.LogInformation(DbResult);
        }
        catch (Exception ex)
        {
            DbResult = $"❌连接失败：{ex.Message}";
            logger.LogError(ex, DbResult);
        }
        finally
        {
            // 确保连接关闭
            if (dbContext.Database.GetDbConnection().State == global::System.Data.ConnectionState.Open)
            {
                await dbContext.Database.CloseConnectionAsync();
            }
        }
    }

    private async Task TestRedisConnection()
    {
        if (await redisService.TestConnectionAsync())
        {
            RedisResult = "✅ 连接成功！Redis 可访问。";
            logger.LogInformation(RedisResult);
        }
        else
        {
            RedisResult = "❌ 连接失败！Redis 不可访问。";
            logger.LogError(RedisResult);
        }
    }
    
    
    private async Task TestDbQuery()
    {
        try
        {
            var users = await dbContext.SysUsers
                .Where(u => u.Status == UserStatusEnum.Normal)
                .ToListAsync();
            DbQueryResult = $"✅ 查询成功！共 {users.Count} 条用户记录。";
            logger.LogInformation(DbQueryResult);
        }
        catch (Exception ex)
        {
            DbQueryResult = $"❌ 查询失败：{ex.Message}";
            logger.LogError(ex, DbQueryResult);
        }
    }
    
    private Task TestPassword()
    {
        const string password = "test01";
        var encoded = PasswordUtil.Encode(password);
        logger.LogInformation($"密码 {password} 加密后为：{encoded}");
        const string ciphertext = "c082037cc55e96919a9d05b14acc2c0a2683140eac27f01b";
        logger.LogInformation($"密码 {password} 与密文 {ciphertext} 匹配：{PasswordUtil.Matches(password,ciphertext)}");
        return Task.CompletedTask;
    }
}